/*
 * Returns given number with commas every 3 digits.
 */
function formatNumber(number) {
  number += '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(number)) {
    number = number.replace(rgx, '$1' + ',' + '$2');
  }
  return number;
}

/*
 * Examples:
 *   plural(5, 'comment', 'comments') // '5 comments'
 *   plural(1, 'comment', 'comments') // '1 comment'
 *   plural(0, 'comment', 'comments') // '0 comments'
 *   plural(10, 'comment', 'comments', true) // 'comments'
 */
function plural(count, singular, plural, omitNumber) {
  return (omitNumber ? '' : formatNumber(count) + ' ') + (count == 1 ? singular : plural);
}

/*
 * Returns given string with special characters properly encoded.
 */
function htmlspecialchars(str) {
  var div = document.createElement('div');
  var text = document.createTextNode(str);
  div.appendChild(text);
  return div.innerHTML;
}

/*
 * Returns given string with special characters properly encoded, with lines wrapped every 15 characters.
 */
function htmlspecialcharsWrap(string) {
  string = htmlspecialchars(string);
  var pattern = '/([a-zA-Z0-9]{15})([a-zA-Z0-9]{15})/gi';
  var replacement = '$1&shy;$2';
  string = string.replace(pattern, replacement);
  string = string.replace(/\r\n/g, "<br/>");
  return string;
}

/*
 * Returns given string with '<br />' or '<br>' inserted before all newlines (\r\n,\n\r,\r,\n)
 */
function nl2br(str, is_xhtml) {
	var breakTag = (is_xhtml || typeof is_xhtml==='undefined') ? '<br />' : '<br>';

	return (str+'').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+breakTag+'$2');
}

/*
 * Returns an appropriate class name for the given count and high/medium thresholds.
 * Used to put a varying amount of emphasis on a number on a page.
 */
function emphasis(count, high, med) {
  return count >= high ? 'high' : (count >= med ? 'med' : 'low');
}

/*
 * Scrolls to the element with the given id and sets the location hash to that id.
 */
function goTo(id) {
  scrollToPosition = $('#' + id).offset().top;
  $('html, body').animate({
    scrollTop: scrollToPosition
  }, 1000);
  setTimeout(function() {
    location.hash = id;
  }, 1100);
}

function createButton(text, onclickHandler, className) {
  return $('<div></div>', {
    'class': 'button_template ' + (className ? className : ''),
    click:   onclickHandler,
    html:    '<div class="button_bg"></div><div class="button_text">' + text + '</div>'
  });
}

function createSideButton(text, onclickHandler, className) {
	if (text == '>')
		text = '<img src="'+ASSET_HOST+'/image/arrow_double.png" class="right_arrow"/>';
	else
		text = '<img src="'+ASSET_HOST+'/image/arrow_double2.png" class="left_arrow"/>';
	return $('<div></div>', {
    'class': 'fan_button ' + (className ? className : ''),
    click:   onclickHandler,
    html:    text
  });
}

function createPagedItemMoreButton(name, text, onclickHandler, className) {
	var sectionClasses = $('#'+name).children().last().attr('class');
	var height = 40;
	var border_top = '';

	if ((sectionClasses!=null && sectionClasses.indexOf('info_item')!=-1)) {
		border_top = '';
	}
	else {
		border_top = 'border-top: 1px solid #3E3E3E;';
	}

	var background_color = $('#'+name).css('background-color');
	if (background_color=='rgba(0, 0, 0, 0)' || name.indexOf("library")!=-1) {
		var ajaxLoaderColor = '';
	}
	else {
		var ajaxLoaderColor = '-white';
		border_top = '';
	}

	var margin_top = height/2-10;
	return $('<div></div>', {
		'class'	: 'pagedItemsMoreButton '+(className ? className : ''),
		click	:	 onclickHandler,
		style	:	'text-align: center; font-weight: bold; height: '+height+'px; '+border_top,
		html	:	'<div id ="'+name+'text" style="margin-top: '+margin_top+'px;margin-bottom: '+margin_top+'px;">'+text+'</div>'+
				'<img id ="'+name+'MoreSpinner" class="spinner moreSpinner" src="'+ASSET_HOST+'/image/ajax-loader'+ajaxLoaderColor+'.gif"'+'style="display: none;">'
	});
}

function reportSpamComment(author,comment) {
	var isPrivate = (location.pathname == "/user_inbox");
	location.href='/feedback?subject=spam&message='+escape("I am reporting a "+(isPrivate ? "direct message" : "comment")+" by "+author+" as inappropriate:\n"+comment+"\n\n"+document.URL);
}

// calculate time to
function timeago(date) {
	var now = new Date();
	var difference = new Date(now.getTime()-Date.parse(date.toString())), epoch = new Date(0);
	var periods = {
		'decade': 'getUTCFullYear()/10',
		'year':   'getUTCFullYear()',
		'month':  'getUTCMonth()',
		'week':   'getUTCDate()/7',
		'day':    'getUTCDate()',
		'hour':   'getUTCHours()',
		'minute': 'getUTCMinutes()',
		'second': 'getUTCSeconds()'
	};
	for (var key in periods) {
		var func = eval('periods.'+key);
		var num = Math.floor(eval('difference.'+func) - eval('epoch.'+func));
		if (num > 0) {
			return plural(num, key, key+'s') + ' ago';
		}
	}
	return '0 seconds ago';
}

var page = {
  currentRequest: null,
  initPart: function(name, id, url, displayHandler, arg, no_cache) {
    var data = LocalStorage.get(name, id);
    if (no_cache || !data || LocalStorage.isStale(name, id)) {
      page.currentRequest = $.ajax({
        url: url,
        success: function(data, status) {
          displayHandler(data, arg);
          LocalStorage.set(name, id, data);
        },
        error: function(data, status) {
          page.displayError(JSON.parse(data.responseText));
          displayHandler(arg);
        }
      });
    } else { displayHandler(data, arg); }
  },
  displayError: function(response) {
    alert("Uh oh. Something went wrong: (" + response.code + ") " + response.message + ".");
  }
};

function addStoryListItem(name, storyItem, displayAuthor){
	if (storyItem.isPrivate == 1)
		var privateImageTag = '<img src="'+ ASSET_HOST +'/image/v2/private.png" alt="private" title="private" style="vertical-align:middle">';
	else
		var privateImageTag = "";
	
	if (displayAuthor){
		var authorDiv = '<div class="author" style="font-size: 13px;">'+htmlspecialchars(storyItem.author)+'</div>';
		var heightOffset = '36px';
	}
	else{
		var authorDiv = '<div class="author"></div>';
		var heightOffset = '20px';
	}
	
	if (storyItem.partCount > 1)
		var partsDiv = '<span class="parts">' + plural(storyItem.partCount, 'part', 'parts') + '</span>';
	else
		var partsDiv = "";
	
	if (storyItem.description != null)
		var description = storyItem.description;
	else
		var description = "";
	
	if (storyItem.completed != null && storyItem.completed == 1)
		var completed = '<img src="'+ ASSET_HOST +'/image/v2/complete.png" alt="Completed" title="Completed" style="margin-bottom: -1px; padding-top: 1px; padding-left: 1px; padding-right: 3px;">';
	else
		var completed = "";
	
	var imageHeight = '100';

	$(name).append(
		'<div class="storyMoreButtonContainer" style="display: none;"></div>');

	$(name).append(
			$('<div></div>')
			.attr({ 'class': 'info_item' })
			.click(function() { document.location.href = 'info.php?id=' + storyItem.id; })
			//.click(function() { read(storyItem.id); })
			.html(
				'<table><tr>' +
				  '<td style="vertical-align: top; padding-right: 10px">' +
					'<img src="'+storyItem.imageurl+'" class="picFrame2" width="64" height="'+imageHeight+'"/>' +
				  '</td>'+
				  '<td style="vertical-align: top;">' +
				  '<h3 class="title" style="font-size:16px; margin-top: -2px; margin-bottom: 1px;">' + htmlspecialchars(storyItem.title) + privateImageTag + '</h3>' +
				  authorDiv +
				  '<div class=\"descriptionBody\" style="overflow:hidden; height:35px;"><div class="descriptionContainer">' + htmlspecialcharsWrap(description) + '</div></div>' +
					'<div style="margin-top: -1px">' +
						partsDiv +
						completed +
						//'<span class="reads ' + emphasis(storyItem.readCount, 2000, 100) + '">' + plural(storyItem.readCount, 'read', 'reads') + '</span>' +
						'<img src="'+ ASSET_HOST +'/image/reads.png" alt="votes" title="votes" style="margin-bottom: -2px; margin-left: 2px; margin-right: 5px;" width="14" height="14">' +
						'<span class="reads ' + emphasis(storyItem.readCount, 2000, 100) + '">'+formatNumber(storyItem.readCount)+'</span>' +
						'<img src="'+ ASSET_HOST +'/image/v2/votes.png" alt="votes" title="votes" style="margin-bottom: -2px; margin-left: 2px; margin-right: 5px;" width="14" height="14">' +
						'<span class="votes ' + emphasis(storyItem.voteCount, 500, 100) + '">'+formatNumber(storyItem.voteCount)+'</span>' +
						'<br/>' +
						'<span class="last_updated">updated ' + storyItem.lastUpdated + '</span>' +
					'</div>' +
				  '</td>' +
				'</tr></table>'
			)
		)

	var storyMoreButtonContainer = $(name).find('.storyMoreButtonContainer').last();
	var title_height = $(name).find('.title').last().height();
	var author_height = $(name).find('.author').last().height();
	var margin_top = title_height+author_height-2;
	storyMoreButtonContainer.append('<div style="height:'+margin_top+'px"></div>'+
	'<div onclick="expand($(this).parent().next().find(\'.descriptionBody\'));$(this).parent().hide();" class="storyMoreButton"></div>'+
	'<img src="'+ ASSET_HOST +'/image/down_arrow.png" class="moreImage" onclick="expand($(this).parent().next().find(\'.descriptionBody\'));$(this).parent().hide();" width="12" height="12" alt="down_arrow.png">');
	
	var body = $(name).find('.descriptionBody').last();
	var container = $(name).find('.descriptionContainer').last();
	var container_height = container.height();
	var lineheight = body.css('line-height');
	if (lineheight == 'normal')
		lineheight = 18;
	else
		lineheight = lineheight.substr(0,lineheight.length-2);
	if ((container.height()) > lineheight*3.5){
		$(name).find('.storyMoreButtonContainer').last().show();
		body.css('height',lineheight*3.2+'px');
	} else{
		body.css('height','auto');
	}
}

function addExpandButtons(storyItemList){
	var body = $(storyItemList).find('.descriptionBody').first();
	var container = body.find('.descriptionContainer').first();
	var count = 0;
	while (count < storyCount){
		var max_height_str = body.css('max-height')+"";
		var max_height = parseInt(max_height_str.substr(0, max_height_str.length-2));
		var title_height = body.parent().find('.title').first().height();
		var author_height = body.parent().find('.author').first().height(); 
		if (container.height() > max_height){
			var moreButtonContainer = body.parent().parent().find('.moreButtonContainer').first();
			moreButtonContainer.find('.moreButtonBody').first().css('height', max_height+'px');
			var margin_top = title_height+author_height-2;
			moreButtonContainer.css('margin-top', margin_top);
			var margin_bottom = (moreButtonContainer.height()+margin_top+3)*-1;
			moreButtonContainer.css('margin-bottom', margin_bottom);
			moreButtonContainer.show();
		}
		body = body.parent().parent().parent().next().find('.descriptionBody').first();
		container = body.find('.descriptionContainer').first();
		count++;
	}
}
